import {useMemo} from 'react';
import {useCollectionsBySpace} from '@/hooks/api/useCollections';
import {countTabs, filterSpaceCollections, mapCollectionsDtoToView} from '@/lib/collections/view';
import type {SpaceCollection} from '@/types';
import type {UseQueryResult} from '@tanstack/react-query';

type UseFilteredSpaceCollectionsResult = UseQueryResult<SpaceCollection[], unknown> & {
    collections: SpaceCollection[];
    filteredCollections: SpaceCollection[];
    totalTabsCount: number;
    collectionsCount: number;
};

/**
 * 统一获取并派生 Dashboard 所需的 SpaceCollection 视图数据。
 */
export function useFilteredSpaceCollections(
    spaceId: number | null,
    searchQuery: string
): UseFilteredSpaceCollectionsResult {
    const queryResult = useCollectionsBySpace<SpaceCollection[]>(spaceId, {
        select: mapCollectionsDtoToView,
    });

    const collections = queryResult.data ?? [];

    const filteredCollections = useMemo(
        () => filterSpaceCollections(collections, searchQuery),
        [collections, searchQuery]
    );

    const totalTabsCount = useMemo(
        () => countTabs(filteredCollections),
        [filteredCollections]
    );

    return {
        ...queryResult,
        collections,
        filteredCollections,
        totalTabsCount,
        collectionsCount: collections.length,
    };
}
